<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>简化阅读器</title>
    <style>
        body {
            margin: 0;
            padding: 0;
            font-family: Arial, sans-serif;
            background-color: #f5f5f5;
        }
        
        .reader-container {
            width: 100%;
            height: 100vh;
            display: flex;
            flex-direction: column;
        }
        
        .reader-header {
            background: #2c3e50;
            color: white;
            padding: 10px 20px;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        
        .back-btn {
            background: #34495e;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
            text-decoration: none;
            display: inline-block;
        }
        
        .book-title {
            margin: 0;
            font-size: 18px;
        }
        
        .pdf-viewer {
            flex: 1;
            display: flex;
            flex-direction: column;
            position: relative;
        }
        
        .pdf-loading {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            background: rgba(255, 255, 255, 0.9);
            z-index: 10;
        }
        
        .loading-spinner {
            width: 40px;
            height: 40px;
            border: 4px solid #f3f3f3;
            border-top: 4px solid #3498db;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-bottom: 20px;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .pdf-canvas-container {
            flex: 1;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
            overflow: auto;
        }
        
        .pdf-canvas {
            border: 1px solid #ddd;
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
            max-width: 100%;
            max-height: 100%;
        }
        
        .page-info {
            background: rgba(0,0,0,0.7);
            color: white;
            padding: 5px 10px;
            border-radius: 15px;
            position: absolute;
            bottom: 20px;
            right: 20px;
            font-size: 14px;
        }
        
        .touch-areas {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            display: flex;
        }
        
        .touch-left, .touch-right {
            flex: 1;
            cursor: pointer;
        }
        
        .touch-left:hover {
            background: rgba(0,0,0,0.05);
        }
        
        .touch-right:hover {
            background: rgba(0,0,0,0.05);
        }
        
        .controls {
            background: #34495e;
            color: white;
            padding: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 20px;
        }
        
        .controls button {
            background: #3498db;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
        }
        
        .controls button:hover {
            background: #2980b9;
        }
        
        .controls button:disabled {
            background: #7f8c8d;
            cursor: not-allowed;
        }
    </style>
</head>
<body>
    <div class="reader-container">
        <header class="reader-header">
            <a href="index.html" class="back-btn">← 返回</a>
            <h1 class="book-title" id="bookTitle">加载中...</h1>
            <div></div>
        </header>

        <main class="pdf-viewer" id="pdfViewer">
            <div class="pdf-loading" id="pdfLoading">
                <div class="loading-spinner"></div>
                <p>正在加载PDF...</p>
            </div>

            <div class="pdf-canvas-container" id="pdfCanvasContainer" style="display: none;">
                <canvas class="pdf-canvas" id="pdfCanvas"></canvas>
            </div>

            <div class="touch-areas" id="touchAreas" style="display: none;">
                <div class="touch-left" onclick="prevPage()"></div>
                <div class="touch-right" onclick="nextPage()"></div>
            </div>

            <div class="page-info" id="pageInfo" style="display: none;">
                <span id="currentPage">1</span> / <span id="totalPages">1</span>
            </div>
        </main>

        <div class="controls">
            <button onclick="prevPage()" id="prevBtn">上一页</button>
            <span id="pageDisplay">1 / 1</span>
            <button onclick="nextPage()" id="nextBtn">下一页</button>
        </div>
    </div>

    <!-- PDF.js -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.min.js"></script>
    
    <script>
        // 设置PDF.js worker
        pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.worker.min.js';
        
        // 全局变量
        let pdfDoc = null;
        let currentPage = 1;
        let totalPages = 0;
        let isLoading = false;
        
        // DOM元素
        const pdfLoading = document.getElementById('pdfLoading');
        const pdfCanvasContainer = document.getElementById('pdfCanvasContainer');
        const pdfCanvas = document.getElementById('pdfCanvas');
        const touchAreas = document.getElementById('touchAreas');
        const pageInfo = document.getElementById('pageInfo');
        const bookTitle = document.getElementById('bookTitle');
        
        // 获取URL参数
        const urlParams = new URLSearchParams(window.location.search);
        const bookId = urlParams.get('book') || 'jinyouth-issue1';
        const initialPage = parseInt(urlParams.get('page')) || 1;
        
        // 生成标题和文件路径
        function generateTitle(bookId) {
            if (bookId.match(/jinyouth-issue(\d+)/i)) {
                const issueNumber = bookId.match(/jinyouth-issue(\d+)/i)[1];
                return `《缙青年》第${issueNumber}期`;
            }
            return bookId;
        }
        
        function generateFilename(bookId) {
            return `${bookId}.pdf`;
        }
        
        // 显示/隐藏元素
        function show(element) {
            element.style.display = '';
        }
        
        function hide(element) {
            element.style.display = 'none';
        }
        
        // 更新页面信息
        function updatePageInfo() {
            document.getElementById('currentPage').textContent = currentPage;
            document.getElementById('totalPages').textContent = totalPages;
            document.getElementById('pageDisplay').textContent = `${currentPage} / ${totalPages}`;
            
            // 更新按钮状态
            document.getElementById('prevBtn').disabled = currentPage <= 1;
            document.getElementById('nextBtn').disabled = currentPage >= totalPages;
        }
        
        // 加载PDF
        async function loadPDF() {
            try {
                console.log('开始加载PDF:', bookId);
                
                isLoading = true;
                const title = generateTitle(bookId);
                const filename = generateFilename(bookId);
                const pdfPath = `pdfs/${filename}`;
                
                // 更新标题
                bookTitle.textContent = title;
                document.title = `${title} - 《缙青年》电子期刊`;
                
                console.log('PDF路径:', pdfPath);
                
                // 加载PDF文档
                const loadingTask = pdfjsLib.getDocument(pdfPath);
                pdfDoc = await loadingTask.promise;
                totalPages = pdfDoc.numPages;
                
                console.log('PDF加载成功，总页数:', totalPages);
                
                // 跳转到指定页面
                currentPage = Math.min(initialPage, totalPages);
                
                // 渲染当前页面
                await renderPage(currentPage);
                
                // 显示PDF
                hide(pdfLoading);
                show(pdfCanvasContainer);
                show(touchAreas);
                show(pageInfo);
                
                updatePageInfo();
                isLoading = false;
                
                console.log('PDF显示完成');
                
            } catch (error) {
                console.error('PDF加载失败:', error);
                alert(`PDF加载失败: ${error.message}`);
                isLoading = false;
            }
        }
        
        // 渲染页面
        async function renderPage(pageNum) {
            if (!pdfDoc || isLoading) return;
            
            try {
                console.log('开始渲染页面:', pageNum);
                
                const page = await pdfDoc.getPage(pageNum);
                const container = pdfCanvasContainer;
                
                // 计算视口
                const containerWidth = container.clientWidth - 40;
                const containerHeight = container.clientHeight - 40;
                
                const originalViewport = page.getViewport({ scale: 1 });
                const scaleX = containerWidth / originalViewport.width;
                const scaleY = containerHeight / originalViewport.height;
                const scale = Math.min(scaleX, scaleY) * 0.9;
                
                const viewport = page.getViewport({ scale });
                
                console.log('视口尺寸:', viewport.width, 'x', viewport.height);
                
                // 设置Canvas尺寸
                const devicePixelRatio = window.devicePixelRatio || 1;
                pdfCanvas.width = viewport.width * devicePixelRatio;
                pdfCanvas.height = viewport.height * devicePixelRatio;
                pdfCanvas.style.width = viewport.width + 'px';
                pdfCanvas.style.height = viewport.height + 'px';
                
                // 渲染
                const context = pdfCanvas.getContext('2d');
                context.scale(devicePixelRatio, devicePixelRatio);
                
                const renderContext = {
                    canvasContext: context,
                    viewport: viewport
                };
                
                await page.render(renderContext).promise;
                
                console.log('页面渲染完成:', pageNum);
                
                // 验证渲染结果
                const imageData = context.getImageData(0, 0, 1, 1);
                const hasContent = imageData.data.some(x => x !== 0);
                console.log('渲染验证:', hasContent ? '有内容' : '无内容');
                
                currentPage = pageNum;
                updatePageInfo();
                
            } catch (error) {
                console.error('页面渲染失败:', error);
                alert(`页面渲染失败: ${error.message}`);
            }
        }
        
        // 上一页
        async function prevPage() {
            if (currentPage > 1) {
                await renderPage(currentPage - 1);
            }
        }
        
        // 下一页
        async function nextPage() {
            if (currentPage < totalPages) {
                await renderPage(currentPage + 1);
            }
        }
        
        // 页面加载完成后初始化
        window.addEventListener('load', () => {
            console.log('页面加载完成，开始初始化');
            loadPDF();
        });
        
        // 键盘事件
        document.addEventListener('keydown', (e) => {
            if (e.key === 'ArrowLeft') {
                prevPage();
            } else if (e.key === 'ArrowRight') {
                nextPage();
            }
        });
    </script>
</body>
</html>
